package com.gthncz.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

import com.gthncz.common.CommonResult;
import com.gthncz.service.JWTAuthenticationService;

import io.jsonwebtoken.ExpiredJwtException;

public class JwtAuthenticationFilter extends GenericFilterBean{
	
	private static final Logger log = LoggerFactory.getLogger(JwtAuthenticationFilter.class);
	
	@Autowired
	private JWTAuthenticationService jwTAuthenticationService;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		log.warn("> JwtAuthenticationFilter doFilter.");
		
		try {
			Authentication authentication = jwTAuthenticationService.getAuthentication((HttpServletRequest) request);
			
			SecurityContextHolder.getContext().setAuthentication(authentication);
			chain.doFilter(request, response);
		} catch (ExpiredJwtException e) {
			HttpServletResponse res = (HttpServletResponse) response;
			res.setContentType("application/json");
			res.setStatus(HttpServletResponse.SC_OK);
			res.getOutputStream().println(new CommonResult(200, "OK", e.getMessage()).toJson());
			//  给出过期提示即可，不需要向下传递信息
			// 如果继续向下传递，由于 authentication 是 null 的，会报 403 Forbidden.
		}
		
	}
	
}
